/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.model.entity.behaviours;

import java.util.LinkedList;
import java.util.Queue;

import org.newdawn.slick.geom.Rectangle;

import ca.usherbrooke.model.entity.IEntityModel;
import ca.usherbrooke.tools.position.Vector2D;

/**
 * @author Cody Stoutenburg
 * 
 */
public class MoveBehaviour extends EntityBehaviour {
	private static final long serialVersionUID = 1L;

	private Float moveSpeed;
	private final Queue<Vector2D> sequenceOfPosition;

	/**
	 * @param model
	 */
	public MoveBehaviour(IEntityModel model) {
		super(model);

		moveSpeed = 0.0f;
		sequenceOfPosition = new LinkedList<Vector2D>();
	}

	public void setMoveSpeed(Float speed) {
		moveSpeed = speed;
	}

	public void clearAllPosition() {
		sequenceOfPosition.clear();
	}

	public void addPosition(Queue<Vector2D> position) {
		sequenceOfPosition.addAll(position);
	}

	private void setTargetCenterPosition(Vector2D center) {
		Rectangle size = this.entity.getSize();
		center.addX(-(size.getWidth() / 2));
		center.addY(-(size.getHeight() / 2));
		entity.setTargetPosition(center);
	}

	public void doLogic(int delta) {
		if (!sequenceOfPosition.isEmpty()) {
			Vector2D target = sequenceOfPosition.peek();
			Vector2D speed = target.sub(entity.getCenterPosition());
			speed.normalize();
			speed = speed.multiply(moveSpeed);

			double distance = entity.getCenterPosition().getDistance(target);

			if (!entity.getTargetPosition().equals(target)) {
				setTargetCenterPosition(target);
			}

			if (distance <= 1) {
				sequenceOfPosition.poll();
			} else if (!entity.getCurrentSpeed().equals(speed)) {
				this.entity.setSpeed(speed);
			}
		}
	}
}
